#!/bin/bash

# Agent智能对话系统启动脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 项目目录
PROJECT_DIR="/Users/colinwang/workspace/ai-agent/agent-demo"

echo -e "${CYAN}🤖 Agent智能对话系统启动脚本${NC}"
echo -e "${CYAN}================================${NC}"

# 检查项目目录
if [ ! -d "$PROJECT_DIR" ]; then
    echo -e "${RED}❌ 项目目录不存在: $PROJECT_DIR${NC}"
    exit 1
fi

cd "$PROJECT_DIR"

# 函数：检查进程是否运行
check_process() {
    local process_name="$1"
    local process_count=$(ps aux | grep -E "$process_name" | grep -v grep | wc -l)
    echo $process_count
}

# 函数：启动Redis
start_redis() {
    echo -e "${BLUE}📡 检查Redis服务状态...${NC}"
    
    if redis-cli ping > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Redis服务已运行${NC}"
    else
        echo -e "${YELLOW}⚠️ Redis服务未运行，正在启动...${NC}"
        redis-server --daemonize yes
        sleep 2
        
        if redis-cli ping > /dev/null 2>&1; then
            echo -e "${GREEN}✅ Redis服务启动成功${NC}"
        else
            echo -e "${RED}❌ Redis服务启动失败${NC}"
            exit 1
        fi
    fi
}

# 函数：启动Agent服务器
start_agent_server() {
    echo -e "${BLUE}🤖 检查Agent服务器状态...${NC}"
    
    local server_count=$(check_process "./server/server")
    
    if [ "$server_count" -gt 0 ]; then
        echo -e "${YELLOW}⚠️ Agent服务器已运行，正在重启...${NC}"
        pkill -f "./server/server"
        sleep 2
    fi
    
    echo -e "${YELLOW}🚀 启动Agent服务器...${NC}"
    nohup ./server/server > server.log 2>&1 &
    
    # 等待服务器启动
    echo -e "${BLUE}⏳ 等待服务器启动...${NC}"
    for i in {1..10}; do
        if curl -s http://localhost:8080/api/agent/stats > /dev/null 2>&1; then
            echo -e "${GREEN}✅ Agent服务器启动成功${NC}"
            break
        fi
        if [ $i -eq 10 ]; then
            echo -e "${RED}❌ Agent服务器启动超时${NC}"
            exit 1
        fi
        sleep 1
        echo -n "."
    done
    echo ""
}

# 函数：显示服务状态
show_status() {
    echo -e "${PURPLE}📊 服务状态检查${NC}"
    echo -e "${PURPLE}=================${NC}"
    
    # Redis状态
    if redis-cli ping > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Redis服务: 运行中${NC}"
    else
        echo -e "${RED}❌ Redis服务: 未运行${NC}"
    fi
    
    # Agent服务器状态
    if curl -s http://localhost:8080/api/agent/stats > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Agent服务器: 运行中 (http://localhost:8080)${NC}"
        
        # 获取Agent统计信息
        local stats=$(curl -s http://localhost:8080/api/agent/stats)
        echo -e "${CYAN}📈 Agent统计信息:${NC}"
        echo "$stats" | python3 -m json.tool 2>/dev/null || echo "$stats"
    else
        echo -e "${RED}❌ Agent服务器: 未运行${NC}"
    fi
}

# 函数：运行功能测试
run_tests() {
    echo -e "${PURPLE}🧪 运行功能测试${NC}"
    echo -e "${PURPLE}===============${NC}"
    
    local session_id="test-$(date +%s)"
    
    # 测试时间查询
    echo -e "${BLUE}🕐 测试时间查询...${NC}"
    local time_result=$(curl -s -X POST -H "Content-Type: application/json" \
        -d "{\"sessionId\": \"$session_id\", \"message\": \"现在北京时间是几点？\"}" \
        http://localhost:8080/api/chat)
    
    if echo "$time_result" | grep -q "北京的当前时间"; then
        echo -e "${GREEN}✅ 时间查询功能正常${NC}"
    else
        echo -e "${RED}❌ 时间查询功能异常${NC}"
    fi
    
    # 测试数学计算
    echo -e "${BLUE}🧮 测试数学计算...${NC}"
    local calc_result=$(curl -s -X POST -H "Content-Type: application/json" \
        -d "{\"sessionId\": \"$session_id\", \"message\": \"计算 12 + 8\"}" \
        http://localhost:8080/api/chat)
    
    if echo "$calc_result" | grep -q "20"; then
        echo -e "${GREEN}✅ 数学计算功能正常${NC}"
    else
        echo -e "${RED}❌ 数学计算功能异常${NC}"
    fi
    
    # 测试普通聊天
    echo -e "${BLUE}💬 测试普通聊天...${NC}"
    local chat_result=$(curl -s -X POST -H "Content-Type: application/json" \
        -d "{\"sessionId\": \"$session_id\", \"message\": \"你好\"}" \
        http://localhost:8080/api/chat)
    
    if echo "$chat_result" | grep -q "你好"; then
        echo -e "${GREEN}✅ 普通聊天功能正常${NC}"
    else
        echo -e "${RED}❌ 普通聊天功能异常${NC}"
    fi
}

# 主程序
main() {
    case "${1:-start}" in
        "start")
            start_redis
            start_agent_server
            show_status
            echo -e "${GREEN}🎉 Agent智能对话系统启动完成！${NC}"
            echo -e "${CYAN}💡 访问地址: http://localhost:8080${NC}"
            echo -e "${CYAN}📚 API文档: 查看 AGENT_ARCHITECTURE_REPORT.md${NC}"
            ;;
        "status")
            show_status
            ;;
        "test")
            run_tests
            ;;
        "stop")
            echo -e "${YELLOW}🛑 停止Agent服务...${NC}"
            pkill -f "./server/server"
            pkill -f "redis-server"
            echo -e "${GREEN}✅ 服务已停止${NC}"
            ;;
        "restart")
            echo -e "${YELLOW}🔄 重启Agent服务...${NC}"
            $0 stop
            sleep 2
            $0 start
            ;;
        "logs")
            echo -e "${BLUE}📋 查看服务器日志...${NC}"
            tail -f server.log
            ;;
        *)
            echo -e "${CYAN}使用方法: $0 [start|stop|restart|status|test|logs]${NC}"
            echo ""
            echo -e "${CYAN}命令说明:${NC}"
            echo -e "  start   - 启动所有服务 (默认)"
            echo -e "  stop    - 停止所有服务"
            echo -e "  restart - 重启所有服务"
            echo -e "  status  - 查看服务状态"
            echo -e "  test    - 运行功能测试"
            echo -e "  logs    - 查看服务器日志"
            ;;
    esac
}

# 执行主程序
main "$@"
